package leetcode.editor.cn.q0xx

import leetcode.editor.cn.ListNode

/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
class Q21 {

    fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
        var h1 = l1
        var h2 = l2
        var cur: ListNode? = ListNode(0)
        val head = cur
        while (h1 != null && h2 != null) {
            if (h1.`val` <= h2.`val`) {
                cur?.next = h1
                h1 = h1.next
            } else {
                cur?.next = h2
                h2 = h2.next
            }
            cur = cur?.next
        }
        if (h1 == null) {
            cur?.next = h2
        } else if (h2 == null) {
            cur?.next = h1
        }

        return head?.next
    }
}